package com.idak.rdv.web.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.idak.rdv.db.User;
import com.idak.rdv.service.UserService;
import com.idak.rdv.web.form.LoginForm;

@Component("loginFormValidator")
public class LoginFormValidator implements Validator {
	
	@Autowired
	private UserService userService;
	public boolean supports(Class<?> aclass) {
		return LoginForm.class.equals(aclass);
	}
	
	public void validate(Object object, Errors errors) {
		if(object instanceof LoginForm){
			LoginForm form = (LoginForm) object;
			User user = userService.findUserByLogin(form.getLogin());
			if(user == null || (user !=null && !user.getPassword().equals(form.getPassword()))){
				errors.rejectValue("login", "login.form.login.inconnu");
			}
			
		}
	}

}
